﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TFSTools.TFSLibrary
{
    public sealed class TFSCustomQueryDefinition : TFSServerEntity
    {
        public TFSCustomQueryDefinition(ITFSConnection connection)
            : base(connection)
        {
            this.SelectFields = new TFSQueryParameterCollection();
            this.WhereFields = new TFSQueryParameterCollection();
        }

        public TFSQueryParameterCollection SelectFields { get; set; }

        public TFSQueryParameterCollection WhereFields { get; set; }

        public string QueryString
        {
            get
            {
                StringBuilder queryString = new StringBuilder();

                if (this.SelectFields != null && this.SelectFields.Any())
                {
                    foreach (var field in this.SelectFields)
                    {
                        if (queryString.Length == 0)
                        {
                            queryString.Append("select ");
                        }
                        else
                        {
                            queryString.Append(", ");
                        }
                        
                        queryString.Append(field.FieldName);
                    }
                }
                else
                {
                    queryString.Append("SELECT ID");
                }

                if (this.WhereFields != null && this.WhereFields.Any())
                {
                    StringBuilder whereClause = new StringBuilder();

                    foreach (var field in this.WhereFields)
                    {
                        if (whereClause.Length == 0)
                        {
                            whereClause.Append(" from WorkItems Where ");
                        }
                        else
                        {
                            whereClause.Append(", ");
                        }

                        whereClause.Append(field.FieldName);
                        whereClause.Append(field.Operator);

                        if (string.IsNullOrEmpty(field.ValueString))
                        {
                            whereClause.Append(field.ValueInt32.ToString());
                        }
                        else
                        {
                            whereClause.Append("'" + field.ValueString + "'");
                        }
                    }

                    queryString.Append(whereClause.ToString());

                    return queryString.ToString();
                }
                else
                {
                    throw new InvalidOperationException("WhereFields must contain items.");
                }
            }
        }
    }
}
